package goperf

import (
	"crypto/rand"
	"encoding/binary"
	"gitee.com/ha666/logs"
	"io"
	"net"
	"sync"
	"time"
)

// 长连接持续发数据(0-4MB随机发送)
func LongRequest() {
	LongLink()
}

//目标端随机，定期端链接测试
func LongLink() {
	const BufSize = 128 * 1024
	var wg sync.WaitGroup

	startTime := time.Now().Unix()
	for i := 0; i < *fConcurrency; i++ {
		wg.Add(1)
		go func() {
			buf := make([]byte, BufSize)
			rand.Read(buf)
			var conn net.Conn
			var err error
			for {
				conn, err = getRandomConn()
				if err != nil {
					logs.Error("get conn error:", err)
					continue
				} else {
					break
				}
			}

			go func() {
				for {
					_, err := conn.Write(buf)
					if err == io.EOF {
						//logs.Error(err)
						break
					} else {
						if err != nil {
							logs.Error(err)
							break
						}
					}
				}
			}()
			go func() {
				for {
					var count uint64
					if err := binary.Read(conn, binary.BigEndian, &count); err != nil {
						//logs.Error(err)
					}
				}
			}()
			//wg.Done()
		}()
	}
	wg.Wait()

	endTime := time.Now().Unix()
	elapsed := endTime - startTime
	if elapsed == 0 {
		logs.Info("Finished in 0 second. Too fast for benchmark.")
		return
	}
	dataAmount := uint64(*fConcurrency) * uint64(*fAmount)

	speed := dataAmount / uint64(elapsed)
	logs.Info("Long link send:", dataAmount, "KB of data sent through", *fConcurrency, "connections in", elapsed, "seconds, with speed", speed, "KB/s.")
}
